﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EditUsers_Better;

namespace EditUsers_Better.ManageUsersModule
{
    public partial class ManageUsersView : Form, IManageUsersView
    {
        private bool IsInCreateMode = false;

        public ManageUsersView()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Presenter.Search(txtSearch.Text);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // Tell the Presenter to create/save the currently selected record
            // Note: the View has a BindingSource control called userBindingSource that is bound to a User object
            // using data binding, and the three TextBox controls at the bottom of the screen 
            // are bound to userBindingSource - hence work on the currently selected record in the Users collection 
            this.userBindingSource.EndEdit();
            if (IsInCreateMode)
            {
                Presenter.Create((User)this.userBindingSource.Current);
                IsInCreateMode = false;
            }
            else
            {
                Presenter.Save((User)this.userBindingSource.Current);
            }

            // Get grid to redraw itself
            this.userDataGrid.Refresh();
        }


        #region IManageUsersView Members

        public void SetResults(IEnumerable<User> searchResults)
        {
            this.userBindingSource.DataSource = searchResults;
            this.userDataGrid.Refresh();
        }

        public void SetStatus(string status)
        {
            this.statusBar.Text = status;
        }

        #endregion

        #region IView<ManageUsersPresenter> Members

        public ManageUsersPresenter Presenter
        {
            get; set;
        }

        #endregion

        private void EnableEditControls(bool enableIt)
        {
            this.txtFirstName.Enabled = enableIt;
            this.txtLastName.Enabled = enableIt;
            this.txtUsername.Enabled = enableIt;
            this.btnSave.Enabled = enableIt;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            // Create a new user
            this.userBindingSource.AllowNew = true;
            this.userBindingSource.AddNew();
            IsInCreateMode = true;
            EnableEditControls(true);
            txtUsername.Focus();
        }

        private void userBindingSource_PositionChanged(object sender, EventArgs e)
        {
            EnableEditControls(userBindingSource.Position > -1);
        }
    }
}